﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Windows.Forms;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application oExcel;
            Excel.Workbook DestWb;
            Excel.Workbook SrcWb; 
            Excel.Worksheet DestFirstSheet;
            Excel.Worksheet SrcSheet;
            string fName;

           
            if (args.Count() < 2)
            {
                Console.Write("Usage: xlsxmerge.exe sourcedir targetfile");
                return;
            }

            string TargetDir = args[0];
            string sTargetPath = args[1];

            string[] filePaths = Directory.GetFiles(TargetDir, "*.xlsx");
            //string sTargetPath = @"z:\3\report.xlsx";

            if (File.Exists(sTargetPath))
            {
                Console.Write("Target file already exists, aborting");
                return;
            }

            if (filePaths.Count() < 2) {
                Console.Write("Too few files in directory (<2), aborting");
                return;
            }

            if (filePaths.Contains(sTargetPath))
            {
                Console.Write("Target file found in source directory, aborting");
                return;
            }

            try
            {
                oExcel = new Excel.Application();
            }
            catch {
                Console.Write("Excel.Application can not be created, abort");
                return;
            }

            oExcel.SheetsInNewWorkbook = 1;
            DestWb = oExcel.Workbooks.Add();
            DestFirstSheet = DestWb.Sheets[1];

            foreach (string fPath in filePaths) {
                fName = Path.GetFileName(fPath);

                try
                {
                    SrcWb = oExcel.Workbooks.Open(fPath);
                }
                catch
                {
                    Console.Write("Could not load " + fName+", abort");
                    return; 
                }

                
                for (int i = 1; i <= SrcWb.Sheets.Count;i++ )
                {
                    SrcSheet = SrcWb.Sheets[i];
                    SrcSheet.Name = fName + (i>1 ? i.ToString() : "");
                    SrcSheet.Copy(DestFirstSheet);
                }
               
                SrcWb.Close(false);
            }

            DestWb.Sheets[DestWb.Sheets.Count].Delete();

            try
            {
                DestWb.SaveAs(sTargetPath);
            }
            catch {
                Console.Write("Could not save " + sTargetPath + ", abort");
            } 
            DestWb.Close();

        }
    }
}
